﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Go;

namespace fhs
{
    public partial class AxisOptionForm : Form
    {
        public enum MoveMode
        {
            相对,
            绝对,
            Jog
        }

        private PointDebugForm _debugForm;
        private Dictionary<PointName.Axis, DataGridViewRow> _axisCoord = new Dictionary<PointName.Axis, DataGridViewRow>();
        private generator _refreshAxisCoord;
        private List<int> _absPoss = new List<int>();
        private List<int> _relPoss = new List<int>();

        public AxisOptionForm(PointDebugForm debugForm)
        {
            _debugForm = debugForm;
            InitializeComponent();
        }

        private MoveMode GetSelectMode()
        {
            if (radioButton_相对.Checked)
            {
                return MoveMode.相对;
            }
            else if (radioButton_绝对.Checked)
            {
                return MoveMode.绝对;
            }
            return MoveMode.Jog;
        }

        public void SetActive(List<PointName.Axis> axiss)
        {
            foreach (DataGridViewRow selectRow in dataGridView1.Rows)
            {
                string name = selectRow.Cells[dataGridView1.Columns["轴名称"].Index].Value.ToString();
                if (axiss.IndexOf(StringToEnum.Convert<PointName.Axis>(name)) >= 0)
                {
                    selectRow.Cells[0].Style.BackColor = Color.FromArgb(255, 128, 128, 255);
                }
                else
                {
                    selectRow.Cells[0].Style.BackColor = Color.White;
                }
            }
        }

        public void SelectAxis(PointName.Axis axis)
        {
            _axisCoord[axis].Selected = true;
        }

        private async Task RefreshAxisCoord()
        {
            while (true)
            {

                await generator.sleep(100);
            }
        }

        private void AxisEditForm_Load(object sender, EventArgs e)
        {
            foreach (var item in Enum.GetValues(typeof(PointName.Axis)))
            {
                DataGridViewRow newRows = new DataGridViewRow();
                newRows.CreateCells(dataGridView1);
                newRows.Cells[dataGridView1.Columns["轴名称"].Index].Value = item.ToString();
                newRows.Cells[dataGridView1.Columns["轴目标"].Index].Value = "0";
                newRows.Cells[dataGridView1.Columns["轴规划"].Index].Value = "0";
                newRows.Cells[dataGridView1.Columns["轴反馈"].Index].Value = "0";
                newRows.Cells[dataGridView1.Columns["轴移动"].Index].Value = "0";
                newRows.Cells[dataGridView1.Columns["轴速度"].Index].Value = "1";
                newRows.Cells[dataGridView1.Columns["加速度"].Index].Value = "0.1";
                newRows.Cells[dataGridView1.Columns["减速度"].Index].Value = "0.1";
                newRows.Cells[dataGridView1.Columns["使能"].Index].Value = false;
                _axisCoord[(PointName.Axis)item] = newRows;
                dataGridView1.Rows.Add(newRows);
                _absPoss.Add(0);
                _relPoss.Add(0);
            }
            radioButton_相对.Checked = true;
            _refreshAxisCoord = generator.tgo(GlobalData.mainStrand, RefreshAxisCoord);
            generator.go(GlobalData.mainStrand, RefState);
        }

        private async Task RefState()
        {
            while (true)
            {
                if (Visible)
                {
                    int i = 0;
                    foreach (KeyValuePair<PointName.Axis, MotionBase> motItem in MotionMgr.motions)
                    {
                        var Row = dataGridView1.Rows[i++];
                        DataGridViewCell axisSts = Row.Cells[dataGridView1.Columns["轴状态"].Index];
                        DataGridViewCell OrgSts = Row.Cells[dataGridView1.Columns["轴原点"].Index];
                        DataGridViewCell posLimitSts = Row.Cells[dataGridView1.Columns["正极限"].Index];
                        DataGridViewCell negLimitSts = Row.Cells[dataGridView1.Columns["负极限"].Index];
                        DataGridViewCell dstPos = Row.Cells[dataGridView1.Columns["轴目标"].Index];
                        DataGridViewCell prfPos = Row.Cells[dataGridView1.Columns["轴规划"].Index];
                        DataGridViewCell encPos = Row.Cells[dataGridView1.Columns["轴反馈"].Index];
                        DataGridViewCell enableSts = Row.Cells[dataGridView1.Columns["使能"].Index];
                        try { dstPos.Value = motItem.Value.DstPos; } catch (Exception) { dstPos.Value = "- - -"; }
                        try { prfPos.Value = motItem.Value.PrfPos; } catch (Exception) { prfPos.Value = "- - -"; }
                        try { encPos.Value = motItem.Value.EncPos; } catch (Exception) { encPos.Value = "- - -"; }
                        try { enableSts.Value = motItem.Value.Enable; } catch (Exception) { enableSts.Value = false; }
                        try
                        {
                            axisSts.Value = motItem.Value.Run ? Properties.Resources.light_green : Properties.Resources.light_gray;
                            OrgSts.Value = motItem.Value.Org == OutBase.State.高 ? Properties.Resources.light_green : Properties.Resources.light_gray;
                            posLimitSts.Value = motItem.Value.PosLimit == OutBase.State.高 ? Properties.Resources.light_green : Properties.Resources.light_gray;
                            negLimitSts.Value = motItem.Value.NegLimit == OutBase.State.高 ? Properties.Resources.light_green : Properties.Resources.light_gray;
                        }
                        catch (System.Exception)
                        {
                            axisSts.Value = OrgSts.Value = posLimitSts.Value = negLimitSts.Value = Properties.Resources.light_red;
                        }
                        await generator.sleep(1);
                    }
                }
                await generator.sleep(100);
            }
        }

        public int GetAxisPos(PointName.Axis axis)
        {
            return int.Parse(_axisCoord[axis].Cells[dataGridView1.Columns["轴规划"].Index].Value.ToString());
        }

        public void SetAxisPos(PointName.Axis axis, int pos)
        {
            MoveMode moveMode = GetSelectMode();
            if (MoveMode.绝对 == moveMode)
            {
                _axisCoord[axis].Cells[dataGridView1.Columns["轴移动"].Index].Value = pos.ToString();
            }
            else if (MoveMode.相对 == moveMode)
            {
                int cpos = GetAxisPos(axis);
                _axisCoord[axis].Cells[dataGridView1.Columns["轴移动"].Index].Value = (pos - cpos).ToString();
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }
            MoveMode moveMode = GetSelectMode();
            if (MoveMode.Jog != moveMode)
            {
                try
                {
                    DataGridViewRow selectRow = dataGridView1.Rows[e.RowIndex];
                    PointName.Axis axis = StringToEnum.Convert<PointName.Axis>(selectRow.Cells[dataGridView1.Columns["轴名称"].Index].Value.ToString());
                    int pos = int.Parse(selectRow.Cells[dataGridView1.Columns["轴移动"].Index].Value.ToString());
                    int vel = int.Parse(selectRow.Cells[dataGridView1.Columns["轴速度"].Index].Value.ToString());
                    double acc = double.Parse(selectRow.Cells[dataGridView1.Columns["加速度"].Index].Value.ToString());
                    double dec = double.Parse(selectRow.Cells[dataGridView1.Columns["减速度"].Index].Value.ToString());
                    bool enable = (bool)selectRow.Cells[dataGridView1.Columns["使能"].Index].Value;
                    switch (dataGridView1.Columns[e.ColumnIndex].Name)
                    {
                        case "正方向":
                            if (MoveMode.绝对 == moveMode)
                            {
                                _debugForm.AbsMoveHandler(axis, pos, vel, acc, dec);
                            }
                            else if (MoveMode.相对 == moveMode)
                            {
                                _debugForm.RelMoveHandler(axis, pos, vel, acc, dec);
                            }
                            break;
                        case "反方向":
                            if (MoveMode.相对 == moveMode)
                            {
                                _debugForm.RelMoveHandler(axis, -pos, vel, acc, dec);
                            }
                            break;
                        case "原点":
                            _debugForm.HomeHandler(axis);
                            break;
                        case "清零":
                            _debugForm.ZeroHandler(axis);
                            break;
                        case "清除":
                            _debugForm.ClearHandler(axis);
                            break;
                        case "使能":
                            _debugForm.EnableHandler(axis, !enable);
                            break;
                        default:
                            break;
                    }
                }
                catch (Exception)
                {
                }
            }
        }
        
        private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (MoveMode.Jog == GetSelectMode())
            {
                try
                {
                    DataGridViewRow selectRow = dataGridView1.Rows[e.RowIndex];
                    PointName.Axis axis = StringToEnum.Convert<PointName.Axis>(selectRow.Cells[dataGridView1.Columns["轴名称"].Index].Value.ToString());
                    int vel = int.Parse(selectRow.Cells[dataGridView1.Columns["轴速度"].Index].Value.ToString());
                    double acc = double.Parse(selectRow.Cells[dataGridView1.Columns["加速度"].Index].Value.ToString());
                    double dec = double.Parse(selectRow.Cells[dataGridView1.Columns["减速度"].Index].Value.ToString());
                    bool enable = (bool)selectRow.Cells[dataGridView1.Columns["使能"].Index].Value;
                    switch (dataGridView1.Columns[e.ColumnIndex].Name)
                    {
                        case "正方向":
                            _debugForm.JogMoveHandler(axis, true, vel, acc, dec);
                            break;
                        case "反方向":
                            _debugForm.JogMoveHandler(axis, false, vel, acc, dec);
                            break;
                        case "原点":
                            _debugForm.HomeHandler(axis);
                            break;
                        case "清零":
                            _debugForm.ZeroHandler(axis);
                            break;
                        case "清除":
                            _debugForm.ClearHandler(axis);
                            break;
                        case "使能":
                            _debugForm.EnableHandler(axis, !enable);
                            break;
                        default:
                            break;
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (MoveMode.Jog == GetSelectMode())
            {
                _debugForm.StopHandler();
            }
        }

        private void button_停止_Click(object sender, EventArgs e)
        {
            _debugForm.StopHandler();
        }

        private void radioButton_相对_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton_相对.Checked)
            {
                int i = 0;
                foreach (DataGridViewRow selectRowItem in dataGridView1.Rows)
                {
                    try
                    {
                        _absPoss[i] = int.Parse(selectRowItem.Cells[dataGridView1.Columns["轴移动"].Index].Value.ToString());
                    }
                    catch (Exception)
                    {
                        _absPoss[i] = 0;
                    }
                    selectRowItem.Cells[dataGridView1.Columns["轴移动"].Index].Value = _relPoss[i].ToString();
                    i++;
                }
                dataGridView1.Columns[dataGridView1.Columns["反方向"].Index].Visible = true;
            }
        }

        private void radioButton_绝对_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton_绝对.Checked)
            {
                int i = 0;
                foreach (DataGridViewRow selectRowItem in dataGridView1.Rows)
                {
                    try
                    {
                        _relPoss[i] = int.Parse(selectRowItem.Cells[dataGridView1.Columns["轴移动"].Index].Value.ToString());
                    }
                    catch (Exception)
                    {
                        _relPoss[i] = 0;
                    }
                    selectRowItem.Cells[dataGridView1.Columns["轴移动"].Index].Value = _absPoss[i].ToString();
                    i++;
                }
                dataGridView1.Columns[dataGridView1.Columns["反方向"].Index].Visible = false;
            }
        }

        private void radioButton_Jog_CheckedChanged(object sender, EventArgs e)
        {
            dataGridView1.Columns[dataGridView1.Columns["反方向"].Index].Visible = true;
        }
    }
}
